<script>
import {
  ref,
  getCurrentInstance,
  reactive,
  onMounted
} from 'vue'

export default {
  setup () {
    const {
      proxy
    } = getCurrentInstance()
    const tim = proxy.tim
    const TIM = proxy.TIM
    console.log('tim', tim)
    // 监听事件，例如：
    tim.on(TIM.EVENT.SDK_READY, function (event) {
      sendPlainMsg('user002', '你好啊')
      getConversationList()
    })
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
    })
    const data = reactive({
      user1: {
        username: 'user001',
        userSig: 'eJwtzL0OgjAYheF76WzIR22pIXGC6OJgoFHDRqSaT5Cf0gpovHcRGM9zkvdD5CF2XkoTn1AHyGramKnS4A0ntq3SAO5ytVme1jVmxHcZgMc4XYv5UX2NWo3OOacAMKvB5988JgA2QtClgvexHDW2C*Ndast3b2kQnSUk-SO0**pSJGao5FF3w6kJ8uK6Jd8fkBYzmw__'
      },
      user2: {
        username: 'user002',
        userSig: 'eJwtzEsLgkAYheH-MuuQ4*Q4JrRK2hQ1YhdwJ8wkH5YN4wUh*u*ZujzPgffDLsfM641jMeMe2GrapE3d0oMm7hrjAL5cja4Ka0mz2A*AMBB8LefHDJacGV0IwQHM2tLrb2EgAQFslgqVY3mg-nZPfBUd1F6dzpV0UYTsupNJ9SzLtn6rIremS3Odbtn3B111Md4_'
      },
      user3: {
        username: 'user003',
        userSig: 'eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwqXFqUUGBsZQqeKU7MSCgswUJStDEwMDMxNTI2NziExqRUFmUSpQ3NTU1MjAwAAiWpKZCxIzMzE3MLM0MoeqLc5MB5pcVRmjb2RUkOpRlucfEe6V7FOekx-gmZjkml2ZElaWWlZgUZXumOKlHVZVlG6rVAsAttAzZA__'
      },
      login_user: '',
      sendMsg: '',
      toUser: ''
    })
    const list = ref([])
    const loading = ref(false)
    const finished = ref(false)
    const loadMsg = () => {
      loading.value = false
    }
    const sendPlainMsg = (toUser, text) => {
      const message = tim.createTextMessage({
        to: toUser,
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
          text: text
        }
      })
      const promise = tim.sendMessage(message)
      promise.then(function (imResponse) {
        // 发送成功
        console.log(imResponse)
      }).catch(function (imError) {
        // 发送失败
        console.warn('sendMessage error:', imError)
      })
    }
    const login = (user) => {
      console.log(user)
      if (user === 'user001') {
        user = data.user1
      } else if (user === 'user002') {
        user = data.user2
      } else if (user === 'user003') {
        user = data.user3
      }
      const promise = tim.login({
        userID: user.username,
        userSig: user.userSig
      })
      promise.then(function (imResponse) {
        console.log(imResponse.data) // 登录成功
        if (imResponse.data.repeatLogin === true) {
          console.log(imResponse.data.errorInfo)
        }
      }).catch(function (imError) {
        console.warn('login error:', imError) // 登录失败的相关信息
      })
    }
    const getConversationList = () => {
      // 获取全量的会话列表
      const promise = tim.getConversationList()
      promise.then(function (imResponse) {
        const conversationList = imResponse.data.conversationList // 全量的会话列表，用该列表覆盖原有的会话列表
        console.log('会话列表', conversationList)
        list.value = conversationList
      }).catch(function (imError) {
        console.warn('getConversationList error:', imError) // 获取会话列表失败的相关信息
      })
    }
    const refresh = () => {
      getConversationList()
    }

    onMounted(() => {
    })
    return {
      list,
      loading,
      finished,
      login,
      loadMsg,
      data,
      refresh,
      sendPlainMsg
    }
  }
}
</script>

<template>
  <div class="root">
    <div>
      <input type="text" v-model="data.login_user"/>
      <van-button type="primary" @click="login(data.login_user)" plain="" size="small">登录</van-button>
      <van-button type="primary" @click="refresh()" plain="" size="small">刷新</van-button>
      <input type="text" v-model="data.sendMsg" placeholder="发送内容"/>
      <input type="text" v-model="data.toUser" placeholder="接收者"/>
      <van-button type="danger" plain @click="sendPlainMsg(data.toUser, data.sendMsg)" size="small">发送</van-button>
    </div>
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="loadMsg">
      <div class="msg-list-item" v-for="item in list" :key="item.conversationID">
        <van-image width="40" height="40" src="https://img.yzcdn.cn/vant/cat.jpeg" round class="user-tx"/>
        <div class="user_profile">
          <span class="username">{{ item.userProfile.userID }}</span>
          <span class="last-msg">{{ item.lastMessage.messageForShow }}</span>
        </div>
        <van-badge :content="item.unreadCount" max="99" class="msg_num" position="none" :show-zero="false"/>
        <van-icon name="arrow"/>
      </div>
    </van-list>
  </div>
</template>

<style lang="less">
.root {
  width: 100%;
  box-sizing: border-box;
  padding: 5px;
}

.msg-list-item {
  width: 100%;;
  display: flex;
  align-items: center;
  padding: 8px;
  box-sizing: border-box;
  background-color: #f5f5f5;
  border-radius: 6px;
  margin: 5px 0;
}

.user_profile {
  width: 100px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0 5px;
  flex-grow: 1;
}

.msg_info {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.last-msg {
  width: 100%;
  color: #ccc;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-align: left;
}

.user-tx {
}

</style>
